<template>
  <div>
    <el-row>
      <!-- span表示份数，offset表示向右的偏移量 -->
      <el-col :span="12" :offset="6">
        <div class="content">
          <h1>欢迎登录</h1>
          <!-- model 表单的数据  rules 校验的规则  label-width 文字的宽度 -->
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm">登录</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { userLogin } from '@/api/index'
export default {
  name: 'MyLogin',
  data () {
    return {
      ruleForm: {
        username: 'zaizai',
        password: 'yd123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入您的姓名', trigger: 'blur' },
          { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入您的密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 点击按钮，提交表单
    submitForm () {
      // this.$refs.ruleForm 获取表单组件
      // validate 组件中自带的检验函数
      // valid校验的结果
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // 校验成功 之后就能通过此处跳转到首页了
          const res = await userLogin(this.ruleForm)
          if (res.code === 200) {
            this.$store.commit('saveUserInfo', res.list)
            // this.$router.push('/')
          }
        } else {
          // 校验失败
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style scoped >
.content {
  height: 400px;
  margin-top: 100px;
  background-color: skyblue;
}
</style>
